<?php

namespace Modules\Api\Service;

use HiCommon\Repository\CheckpointMakeDateRepository;
use HiCommon\Repository\RepairstoreTypeRepository;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\RepairstoreGoodsRepository;
use HiCommon\Repository\MaintainShopRepository;
use HiCommon\Repository\UsersVehicleRepository;
use HiCommon\Service\CommonService;
use HiCommon\Service\ShopCheckpointProductService;


class ShopService extends BaseService
{
    /**
     * 获取门店列表（维修店）
     *
     * 2019 12 02
     **/
    public function get_shop_list(array $arrInput)
    {
        try {
            if (empty($arrInput['lon']) || empty($arrInput['lat'])) {
                return hello_error('用户所在的经纬度不能为空');
            }

            $arr_list = ShopRepository::api_get_shop_list($arrInput);
            $shop = list_page_data($arr_list);
            $list = [];
            foreach ($shop['data'] as $key => $value) {
                $shop_type = '';
                if ($value['shop_type'] == 1) {
                    $shop_type = '直营店';
                } elseif ($value['shop_type'] == 2) {
                    $shop_type = '加盟店';
                }
                $arr_input = [
                    'start_longitude' => $arrInput['lon'],
                    'start_latitude' => $arrInput['lat'],
                    'end_longitude' => $value['longitude'],
                    'end_latitude' => $value['latitude'],
                ];

                //重新计算距离
                $distance = CommonService::api_location_distance($arr_input);

                $list['shop'][] = [
                    'shop_id' => $value['id'],
                    'shop_logo' => $value['logo']['full_src'],
                    'shop_name' => $value['name'],
                    'company_name' => $value['company_name'],
                    'address' => str_replace(',', '', $value['area_name']['mername']) . $value['address'],
                    'distance' => $distance['state'] == 0 ? $distance['data']['en_default'] : '0.00 km',
                    'order_num' => $value['store_order_num_count'] + $value['repair_order_num_count'],
                    'shop_type' => $shop_type,
                    'score' => $value['score']
                ];
            }
            $list['page'] = $shop['page_data'];

            return hello_success('获取成功', $list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     *  获取门店详情
     *
     *  2019 12 03
     **/
    public function get_shop_info(array $arrInput)
    {
        try {
            $shop_id = intval($arrInput['shop_id']);
            if (empty($shop_id)) {
                return hello_error('门店id不能为空');
            }
            $userId = $arrInput['user_id'];

            $arrInput['with'] = ['area_name', 'shop_img', 'master', 'collect' => function ($query) use ($userId) {
                $query->where(['type' => 5, 'user_id' => $userId]);
            }];
            $arrInput['where'] = ['id' => $shop_id];
            $shop_obj = ShopRepository::get_one($arrInput);

            if ($shop_obj->first()) {
                $result['shop'] = self::shop_data_handle($shop_obj, $arrInput);//门店基础信息
                $result['recommend'] = self::recommend($shop_obj->id);//推荐的数据
                return hello_success('获取成功', $result);
            }

            return hello_error('门店不存在');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 商品详情数据处理
     */
    public function shop_data_handle($shop_obj, $arrInput)
    {
        $shop = $shop_obj->toArray();
        $shop_img = [];

        foreach ($shop['shop_img'] as $value) {
            $shop_img[] = $value['img']['full_src'];
        }
        foreach ($shop['master'] as &$val) {
            $val['img'] = $val['img']['full_src'];
        }
        $arr_input = [
            'start_longitude' => $arrInput['lon'],
            'start_latitude' => $arrInput['lat'],
            'end_longitude' => $shop['longitude'],
            'end_latitude' => $shop['latitude'],
        ];

        //重新计算距离
        $distance = CommonService::api_location_distance($arr_input);

        $info = [
            'shop_id' => $shop['id'],
            'shop_name' => $shop['name'],
            'longitude' => $shop['longitude'],
            'latitude' => $shop['latitude'],
            'score' => $shop['score'],//门店评分
            'shop_phone' => $shop['phone'],
            'business_hours' => substr($shop['start_time'], 0, 5) . ' - ' . substr($shop['end_time'], 0, 5),
            'address' => str_replace(',', '', $shop['area_name']['mername']) . $shop['address'],
            'distance' => $distance['state'] == 0 ? $distance['data']['en_default'] : '0.00 km',
            'order_num' => $shop['store_order_num_count'] + $shop['repair_order_num_count'],
            'collect' => $shop['collect'] ? true : false,
            'shop_img' => $shop_img,
            'shop_master' => $shop['master']
        ];

        return $info;
    }

    /**
     * 获取门店推荐数据
     */
    public function recommend($shop_id)
    {
        //商品
        $option['where'] = ['repairstore_id' => $shop_id, 'is_recommend' => 1, 'type' => 1, 'status' => 1];
        $option['with'] = ['product_info'];
        $option['limit'] = 6;
        $option['field'] = ['id', 'name', 'price', 'pic_url'];
        $goods = GoodsRepository::by_where_limit($option);

        foreach ($goods as &$value) {
            $value['product_info'] = reset($value['product_info']);
            $value['pic_url'] = $value['pic_url']['full_src'];
        }

        //服务
        $service['where'] = ['repairstore_id' => $shop_id, 'is_recommend' => 1, 'status' => 1];
        $service['with'] = ['pic'];
        $service['limit'] = 6;
        $service['field'] = ['id', 'name', 'price'];
        $repair = RepairstoreGoodsRepository::by_where_limit($service);

        foreach ($repair as $key => &$val) {
            $val['pic'] = reset($val['pic'])['picurl']['full_src'];
        }

        $user_id = api_user_id(); //用户id
        $vehicle_model_pid = 0;
        if ($user_id) {
            $where = ['user_id' => $user_id, 'users_company_id' => 0, 'is_default' => 1];
            $vehicle['with'] = ['vehicle_model'];
            $vehicle['field'] = ['vehicle_model_id'];
            $vehicle_obj = UsersVehicleRepository::get_one_by_where($where, $vehicle);
            if ($vehicle_obj->first()) {
                $vehicle_model = $vehicle_obj->toarray();
                $vehicle_model_pid = $vehicle_model['vehicle_model']['parentid'];//汽车型号的父及id（用于筛选）
            }
        }

        //保养
        $input['where'] = ['shop_id' => $shop_id];
        $input['with'] = ['son_config', 'maintain_shop_goods', 'maintain_vehicle_model'];
        $input['limit'] = 6;
        $input['field'] = ['id', 'shop_id', 'maintain_config_id', 'custom_title'];
        $maintain_shop = MaintainShopRepository::by_where_limit($input, $vehicle_model_pid);

        $maintain = [];
        foreach ($maintain_shop as $item) {
            $total_price = 0.00;
            foreach ($item['maintain_shop_goods'] as $v) {
                if ($v['product']) {
                    $total_price += $v['product']['price'] * $v['num'];
                }
            }
            if ($total_price > 0) {
                $maintain[] = [
                    'maintain_id' => $item['id'],
                    'name' => $item['custom_title'] ?? $item['son_config']['name'],
                    //'name' => $item['son_config']['name'],
                    'price' => number_format_money($total_price),
                    'pic' => reset($item['maintain_shop_goods'])['product']['pic']['full_src'],
                ];
            }
        }

        return ['goods' => $goods, 'repair' => $repair, 'maintain' => $maintain];
    }

    /**
     * 检测机构列表
     *
     * @param $arr_search
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_checkpoint_list($arr_search)
    {
        $arr_search['status'] = 1;
        $arr_search['state'] = 1;

        $res = \HiCommon\Service\ShopService::api_checkpoint_list($arr_search);
        if ($res['state'] != 0 || $res['data']['data_count'] == 0) {
//            return $res;
        } else {
            $arr_this_data = $res['data']['data'];

            $arr_data = [];
            foreach ($arr_this_data as $value) {
                $arr_checkpoint_service_type = array_values(list_array_to_key_value($value['checkpoint_service_type'], 'title'));
                $s_address = $value['province_name']['name'] . $value['city_name']['name'] . $value['area_name']['name'] . $value['address'];
                $arr_data[] = [
                    'id' => $value['id'],
                    'name' => $value['name'],
                    'cover_img' => $value['logo']['full_src'],
                    'check_score' => $value['check_score'],
                    'tag' => $arr_checkpoint_service_type,
                    'type' => $value['type']['title'],
                    'address' => $s_address,
                    'distance' => $value['distance'],
                    'phone' => $value['phone'],
                    'longitude' => $value['longitude'],
                    'latitude' => $value['latitude'],
                ];
            }

            $res['data']['data'] = $arr_data;
        }
        return $res;
    }

    /**
     * 检测机构-商家详情 [商家详情+时间段+年检费用]
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_checkpoint_detail($n_id)
    {
        if ($n_id <= 0) {
            return hello_error('数据id不能为空');
        }
        $res = \HiCommon\Service\ShopService::api_checkpoint_detail($n_id);

        if ($res['state'] == 0) {
            $data = $res['data'];
            $arr_checkpoint_service_type = array_values(list_array_to_key_value($data['checkpoint_service_type'], 'title'));
            $s_address = $data['province_name']['name'] . $data['city_name']['name'] . $data['area_name']['name'] . $data['address'];

            $arr_appointment_day = $data['appointment_day'];
            foreach ($arr_appointment_day as $key => &$value) {
                $am_is_disabled = 2;
                $am_is_full = 2;
                $pm_is_disabled = 2;
                $pm_is_full = 2;
                $n_now_time = time();
                $n_am_remain = 0;
                $n_pm_remain = 0;

                if ($key == 0) {
                    $am_time = strtotime($value['day'] . ' ' . trim(explode('-', $value['am_time'])[0]) . ':00') - 2 * 60 * 60;
                    $pm_time = strtotime($value['day'] . ' ' . trim(explode('-', $value['pm_time'])[0]) . ':00') - 2 * 60 * 60;
                    if ($n_now_time >= $am_time) {
                        $am_is_disabled = 1;
                    }
                    if ($n_now_time >= $pm_time) {
                        $pm_is_disabled = 1;
                    }

                }


                if ($value['am_num'] <= $value['am_order']) {
                    $am_is_full = 1;
                } else {
                    $n_am_remain = $value['am_num'] - $value['am_order'];
                }
                if ($value['pm_num'] <= $value['pm_order']) {
                    $pm_is_full = 1;
                } else {
                    $n_pm_remain = $value['pm_num'] - $value['pm_order'];
                }

                $value['am_remain'] = $n_am_remain;
                $value['pm_remain'] = $n_pm_remain;
                $value['am'] = [
                    'is_disabled' => $am_is_disabled,
                    'is_full' => $am_is_full,
                ];

                $value['pm'] = [
                    'is_disabled' => $pm_is_disabled,
                    'is_full' => $pm_is_full,
                ];
            }
            $arr_data = [
                'id' => $data['id'],
                'name' => $data['name'],
                'cover_img' => $data['logo']['full_src'],
                'check_score' => $data['check_score'],
                'tag' => $arr_checkpoint_service_type,
                'type' => $data['type']['title'],
                'address' => $s_address,
//              'distance'=>$data['distance'],
                'phone' => $data['phone'],
                'longitude' => $data['longitude'],
                'latitude' => $data['latitude'],
                'appointment_day' => $arr_appointment_day,
                'expenses' => $data['expenses'],
            ];
            $res['data'] = $arr_data;
        }

        return $res;

    }

    /**
     * 检测机构-规格参数价目表
     *
     * @param int $n_shop_id
     * @param int $n_use_state
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_checkpoint_products($n_shop_id = 0, $n_use_state = 0)
    {
        $res = ShopCheckpointProductService::api_list_by_shopid($n_shop_id, $n_use_state);
        if ($res['state'] == 0) {
            $data = $res['data'];
            $arr_specs = $data['specs'];
            if (count($arr_specs) > 0) {
                foreach ($arr_specs as &$value) {
                    $value = [
                        'id' => $value['id'],
                        //                  'shop_id'=>$value['shop_id'],
                        'pid' => $value['pid'],
                        'name' => $value['name'],
                        //                  'is_goto_use'=>$value['is_goto_use'],
                        //                  'is_driving_use'=>$value['is_driving_use'],
                        'level' => $value['level'],
                        'child' => $value['_child'],
                    ];

                    if (count($value['child']) > 0) {
                        foreach ($value['child'] as &$vv) {
                            $vv = [
                                'id' => $vv['id'],
                                'pid' => $vv['pid'],
                                'name' => $vv['name'],
                                'price' => $vv['price'],
                                'level' => $vv['level'],
                            ];
                        }
                    }

                }

            }
            $res['data'] = $arr_specs;

        }

        return $res;
    }


    /**
     * 车检维修专区-首页
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_shop_special_performance()
    {
        $arr_data = [];

        //banner
        $arr_input['type'] = 1;
        $res = ActivityService::banner($arr_input);
        if ($res['state'] != 0) {
            return $res;
        }
        $arr_data['banner'] = $res['data'];

        //年检须知
        $arr_option['field'] = ['id', 'cate', 'name', 'sort'];
        $res = CommonService::api_year_check_note($arr_option);
        if ($res['state'] != 0) {
            return $res;
        }
        $arr_data['year_check_note'] = $res['data'];

        return hello_success('成功', $arr_data);

    }


    /**
     * 车检维修专区-首页  获取所有维修店服务商品（按距离等条件筛选）
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all_shop_repair_goods($option)
    {
        try {
            if (!$option['lon'] || !$option['lat']) {
                return hello_error('经纬度参数错误');
            }

            $data = RepairstoreGoodsRepository::small_get_list($option);
            $data = list_page_data($data);

            foreach ($data['data'] as $key => &$value) {
                $value['type_id'] = $value['type']['id'];
                $value['type'] = $value['type']['title'];
                $value['shop_id'] = $value['shop']['id'];
                $value['shop_name'] = $value['shop']['name'];
                $value['shop_logo'] = $value['pic'][0]['picurl']['full_src'] ?? $value['shop']['logo']['full_src'];

                $city = str_replace(',', '', $value['shop']['area_name']['mername']);

                $value['shop_address'] = $city . ' ' . $value['shop']['address'];

                unset($value['shop']);
                unset($value['pic']);
            }

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *    获取维修种类
     */
    public function get_repair_type()
    {
        try {
            $data = RepairstoreTypeRepository::get_all(['status' => 1], ['id', 'title']);

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

}